var Base = require('./baseModel.js'),
 	util = require('util'),
 	crypt = require('../middleware/crypto.js');
var b = Base.prototype;

function Model() {
	Base.apply(this, arguments);
}
util.inherits(Model, Base);

Model.usernameDoesNotExist = function(username,callback) {
	sql = "SELECT * from browsergame.user WHERE user.username = "+"'"+username+"'";
	console.log(sql);
	b.db.query(sql,function(err,result) {
		console.log(result.length);
		if (result.length >= 1) {
			callback(false);
		} else {
			callback(true);
		}
	})
} 

Model.prototype.auth = function(req,res,usrname,password,callback) {
	sql = "SELECT * FROM browsergame.user WHERE user.username = " + "'"+usrname+"'";
	b.db.query(sql, function(err,result) {
		console.log(err);
		console.log(result);
		if (result.length == 0) {
			var err = "username does not exist";
			callback(err, false);
		} else {
			var usr = result[0].username;
			var db_pwd = result[0].password;
			var salt = result[0].salt;
			crypt.checkEncrypt(password,salt, function(hash) {
				if(db_pwd == hash) {
					req.session.uid = result[0].user_id;
					var err = null;
					callback(err,true);
				} else {
					var err = "password does not match";
					callback(err,false);
				}
			});


		}

	
		

	});
}

Model.prototype.create = function(username,password,callback) {
	
	Model.usernameDoesNotExist(username, function(result){
		if (result) {
			crypt.encrypt(password,function(hash_password,hash_salt){
	    		console.log(password);
		    	console.log(hash_password.length + ' | ' + hash_salt.length);
				var sql = "INSERT INTO browsergame.user(`username`,`password`,`salt`) VALUES('"+username+"','"+hash_password+"','"+hash_salt+"')";
				b.db.query(sql,function(err,result) {
						b.req.session.uid = result.insertId;
						var uid = result.insertId;
						console.log(b.name);
						callback(uid);
				});

			});
		} else {
			console.log('username already exist!');
		}

	});
		
}




var model = new Model('UserModel',1.0);
module.exports = model;

